package cn.example.easy_excel_demo.module.controller;

import cn.example.easy_excel_demo.module.domain.User;
import cn.example.easy_excel_demo.module.domain.UserExample;
import cn.example.easy_excel_demo.module.domain.vo.UserVO;
import cn.example.easy_excel_demo.module.service.UserService;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Api(tags = "FileDownController", description = "文件下载接口")
@Controller
@RequestMapping(value = "/")
public class FileDownController {

    @Autowired
    private UserService userService;

    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetmL.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("fileName").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition","attachment;utf-8;filename="+fileName+".xlxs");
            response.setHeader("Access-Control-Expose-Headres","Content-Disposition");
            //查询用户列表
            List<User> userList = userService.queryAll(new UserExample());
            //表现层属性赋值
            ArrayList<UserVO> voList = new ArrayList<>();
            for (User user : userList) {
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user,userVO);
                voList.add(userVO);
            }
            //模板导出设置
            InputStream inputStream = new ClassPathResource("ExcelFile/dome文件模板.xlsx").getInputStream();//模板文件引用
            EasyExcel.write(response.getOutputStream(),UserVO.class)
//                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .withTemplate(inputStream)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("模板")
                    .doWrite(voList);

        } catch (Exception e) {
            e.printStackTrace();
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            HashMap<String, String> map = new HashMap<>();
            map.put("status", "failure");
            map.put("message", "文件下载失败" + e.getMessage());
            response.getWriter().println(map.toString());
        }
    }
}
